<?php

/**
 * 短信相关控制器
 */

namespace app\common\sms;

use app\BaseController;
use think\facade\Cache;
use app\common\sms\ZtSmsCode;

class SmsService extends BaseController
{
    /**
     *     助通短信
     *
     * @param [type] $phone
     * @return void
     */
    public static function sendZtSms($phone)
    {
        if(self::isSend($phone)){
            error('请勿频繁发送');
        }
        $sms_data = [
            'sms_code_key' => time().rand(1000, 9999),
            'sms_code' => mt_rand(100000, 999999),
        ];

        $url = "http://www.ztsms.cn/sendNSms.do";//提交地址
        $send = new ZtSmsCode($url);
        $data = array(
            'content' => "【点度】您的验证码是" . $sms_data['sms_code'],//短信内容
            'mobile' => $phone,//手机号码
        );
        $send->data = $data;//初始化数据包
        $res = $send->sendSMS('POST');//GET or POST
        $res = explode(',', $res);
        if ($res[0] != 1) {
            error($res[1]);
        }
        Cache::set($sms_data['sms_code_key'], $sms_data['sms_code'], 60);
        self::setSendTime($phone);
        return $sms_data;
    }

    /**
     * 查询剩余短信数量
     *
     * @return void
     */
    public static function sumSms()
    {
        $url = "https://api.mix2.zthysms.com/v2/balance";//提交地址
        $send = new ZtSmsCode($url);
        $res = $send->sumSms();
        $res = json_decode($res, true);
        if ($res['code'] == 200) {
            return $res['sumSms'];
        } else {
            error($res);
        }
    }

    /**
     * 设置可再次发送时间
     *
     * @param [type] $mobile
     * @return void
     */
    public static function setSendTime($mobile, $expire = 60)
    {
        $key = 'sms_coed:'.$mobile;
        Cache::set($key, 1, $expire);
    }

    /**
     * 判断是否可以再次发送短信
     *
     * @param [type] $mobile
     * @return boolean
     */
    public static function isSend($mobile): bool
    {
        $key = 'sms_coed:'.$mobile;
        if (Cache::get($key)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断短信验证码是否正确
     *
     * @param string $sms_code_key
     * @param integer $sms_code
     * @return void
     */
    public static function checkSmsCode($sms_code_key, $sms_code)
    {
        $cache_sms_code = Cache::get($sms_code_key);
        if ($cache_sms_code === false) {
            error('验证码错误');
        } else {
            // 判断输入的验证码是否正确
            if ($sms_code != $cache_sms_code) {
                error('验证码错误');
            }
        }
    } 
}
